<template>
  <div class="modal">
    <el-dialog
      v-model="dialogVisible"
      :title="isNewRef ? '新建社团' : '编辑社团'"
      width="30%"
      center
    >
      <div class="form">
        <el-form
          :model="formData"
          :rules="formRules"
          label-width="80px"
          size="large"
          ref="formRef"
        >
          <el-form-item label="社团名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入社团名称" />
          </el-form-item>
          <el-form-item label="社长" prop="leaderName">
            <el-input
              v-model.number="formData.leaderName"
              placeholder="请输入社长"
            />
          </el-form-item>
          <el-form-item label="社团描述" prop="description">
            <el-input
              type="textarea"
              v-model="formData.description"
              placeholder="请输入社团描述"
            />
          </el-form-item>
          <el-form-item label="社团头像" prop="club_avatar">
            <template #default>
              <el-upload
                class="avatar-uploader"
                :action="`${BASE_URL}/file/avatar`"
                :headers="{
                  Authorization: loginStore.token // 假设 token 是从 Vuex 中获取的
                }"
                accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                name="avatar"
              >
                <img
                  v-if="formData.club_avatar"
                  :src="formData.club_avatar"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </template>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import useLoginStore from '@/store/login/login'
import { ElMessage } from 'element-plus'
import useClubStore from '@/store/main/club/club'
import type { FormRules, ElForm, UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { BASE_URL } from '@/service/config'

// 1.定义内部的属性
const dialogVisible = ref(false)
const clubStore = useClubStore()
const formData = reactive<any>({
  name: '',
  leaderName: '',
  description: '',
  club_avatar: ''
})
const formRules: FormRules = {
  name: [{ required: true, message: '请输入社团名称', trigger: 'blur' }],
  leaderName: [
    { required: true, message: '请输入社团用户名', trigger: 'blur' }
  ],
  description: [{ required: true, message: '请输入社团描述', trigger: 'blur' }],
  club_avatar: [{ required: true, message: '上传头像', trigger: 'blur' }]
}
const formRef = ref<InstanceType<typeof ElForm>>()
const isNewRef = ref(true)
const editData = ref()

// 2.定义设置dialogVisible方法
function setModalVisible(isNew: boolean = true, itemData?: any) {
  dialogVisible.value = true
  isNewRef.value = isNew
  if (!isNew && itemData) {
    for (const key in formData) {
      formData[key] = itemData[key]
    }
    editData.value = itemData
  } else {
    // 新建数据
    for (const key in formData) {
      formData[key] = ''
    }
    editData.value = null
  }
}

// 3.点击了确定的逻辑
async function handleConfirmClick() {
  dialogVisible.value = false
  formRef.value?.validate(async (valid) => {
    if (valid) {
      if (!isNewRef.value && editData.value) {
        // 编辑用户的数据
        await clubStore.editClubDataAtion(editData.value.id, formData)
        ElMessage({
          type: 'success',
          message: '修改社团成功'
        })
      } else {
        // 创建新的用户
        await clubStore.newClubDataAction(formData)
        ElMessage({
          type: 'success',
          message: '创建社团成功'
        })
      }
    }
  })
}

// 上传图片
const loginStore = useLoginStore()
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  console.log(response)
  formData.club_avatar = response.data.tempUrl
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 暴露的属性和方法
defineExpose({ setModalVisible })
</script>

<style lang="less" scoped>
.form {
  padding: 0 20px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
